﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.WebTesting;
using Microsoft.VisualStudio.TestTools.WebTesting.Rules;

namespace QA.TFS.Loops
{
    public class ListLoopCounting<T> : CountingLoopRule
    {

        List<T> lstValores = new List<T>();

        public delegate List<T> fillList(WebTestContext context);
        public delegate void checkIsMet(WebTestContext context, int num);

        public event fillList OnFillList;
        public event checkIsMet OnCheckIsMet;

        public override void CleanUp(object sender, ConditionalEventArgs e)
        {
            base.CleanUp(sender, e);
        }

        public override void Initialize(object sender, ConditionalEventArgs e)
        {
            this.IterationsCount = 0;

            lstValores = new List<T>();
            if (OnFillList != null)
                lstValores = OnFillList(e.WebTest.Context);

            this.IterationsCount = lstValores.Count;

            e.WebTest.Context.Add(this.ContextParameterName, 0);
        }

        public override void CheckCondition(object sender, ConditionalEventArgs e)
        {
            base.CheckCondition(sender, e);

            Int32 num = Convert.ToInt32(int.Parse(e.WebTest.Context[this.ContextParameterName].ToString()));
            e.WebTest.Context[this.ContextParameterName] = num;
            if (num <= lstValores.Count)
            {
                if (OnCheckIsMet != null)
                    OnCheckIsMet(e.WebTest.Context, num);
            }
        }

    }
}
